package com.blog.cmrpersonalblog.service.impl;

import com.blog.cmrpersonalblog.dto.article.response.UserArticleDetailResponse;
import com.blog.cmrpersonalblog.dto.article.request.UserArticleCreateRequest;
import com.blog.cmrpersonalblog.dto.user.request.UserArticleUpdateRequest;
import com.blog.cmrpersonalblog.dto.article.response.UserArticleResponse;
import com.blog.cmrpersonalblog.dto.user.response.UserInteractionStatus;
import com.blog.cmrpersonalblog.entity.Article;
import com.blog.cmrpersonalblog.entity.ArticleTag;
import com.blog.cmrpersonalblog.entity.ArticleCategory;
import com.blog.cmrpersonalblog.enums.ArticleStatus;
import com.blog.cmrpersonalblog.enums.RankingType;
import com.blog.cmrpersonalblog.mapper.ArticleMapper;
import com.blog.cmrpersonalblog.mapper.CategoryMapper;
import com.blog.cmrpersonalblog.mapper.TagMapper;
import com.blog.cmrpersonalblog.service.ArticleTagRelationService;
import com.blog.cmrpersonalblog.service.MarkdownService;
import com.blog.cmrpersonalblog.service.NotificationService;
import com.blog.cmrpersonalblog.service.RankingService;
import com.blog.cmrpersonalblog.service.TagManagementService;
import com.blog.cmrpersonalblog.service.UserArticleService;
import com.blog.cmrpersonalblog.service.UserActivityService;
import com.blog.cmrpersonalblog.utils.HtmlUtils;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 用户端文章服务实现
 */
@Slf4j
@Service
public class UserArticleServiceImpl implements UserArticleService {

    @Resource
    private ArticleMapper articleMapper;

    @Resource
    private MarkdownService markdownService;

    @Resource
    private RankingService rankingService;

    @Resource
    private ArticleTagRelationService articleTagRelationService;

    @Resource
    private CategoryMapper categoryMapper;

    @Resource
    private TagMapper tagMapper;

    @Resource
    private UserActivityService userActivityService;

    @Resource
    private TagManagementService tagManagementService;

    @Resource
    private com.blog.cmrpersonalblog.mapper.UserStatsMapper userStatsMapper;

    @Resource
    private NotificationService notificationService;

    @Override
    public UserArticleDetailResponse getArticleDetail(Long articleId, Long userId, boolean updateViewCount) {
        log.info("用户获取文章详情: articleId={}, userId={}, updateViewCount={}", articleId, userId, updateViewCount);
        
        try {
            // 查询文章基本信息
            UserArticleDetailResponse article = articleMapper.selectUserArticleDetail(articleId);
            if (article == null) {
                throw new RuntimeException("文章不存在");
            }

            // 检查文章状态和权限
            // 如果文章未发布，只有文章作者才能查看
            if (!isArticlePublished(article)) {
                if (!isArticleAuthor(articleId, userId)) {
                    log.warn("文章状态检查失败: articleId={}, status={}, userId={}", articleId, article.getStatus(), userId);
                    throw new RuntimeException("文章未发布或已下架");
                }
                log.info("文章作者查看自己的未发布文章: articleId={}, userId={}", articleId, userId);
            }

            // 处理内容转HTML（根据编辑器类型）
            if (article.getContent() != null) {
                try {
                    // 如果是Markdown编辑器，进行Markdown转HTML
                    if (article.getEditorTypes() == null || article.getEditorTypes() == 1) {
                        article.setHtmlContent(markdownService.convertToHtml(article.getContent()));
                    } else {
                        // 富文本编辑器，内容本身就是HTML，直接使用
                        article.setHtmlContent(article.getContent());
                    }
                } catch (Exception e) {
                    log.warn("内容转换失败: articleId={}, editorTypes={}", articleId, article.getEditorTypes(), e);
                    article.setHtmlContent(article.getContent()); // 降级处理
                }
            }

            // 计算阅读时长和字数
            calculateReadingMetrics(article);

            // 处理标签
            processArticleTags(article);

            // 获取用户交互状态
            if (userId != null) {
                UserInteractionStatus status = getUserInteractionStatus(articleId, userId);
                article.setIsLiked(status.getIsLiked());
                article.setIsCollected(status.getIsCollected());
                if (article.getAuthor() != null) {
                    article.getAuthor().setIsFollowed(status.getIsFollowedAuthor());
                }
            }

            // 获取相关文章推荐
            List<UserArticleDetailResponse.RelatedArticleInfo> relatedArticles = getRelatedArticles(articleId, 5);
            article.setRelatedArticles(relatedArticles);

            // 设置SEO信息
            setSeoInfo(article);

            // 更新浏览量（异步处理）
            if (updateViewCount) {
                incrementViewCountAsync(articleId, userId);
            }

            log.info("文章详情获取成功: articleId={}, title={}", articleId, article.getTitle());
            return article;

        } catch (Exception e) {
            log.error("获取文章详情失败: articleId={}", articleId, e);
            throw new RuntimeException("获取文章详情失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional
    public void incrementViewCount(Long articleId, Long userId, String ipAddress, String userAgent) {
        log.debug("增加文章浏览量: articleId={}, userId={}", articleId, userId);

        try {
            // 获取文章信息
            Article article = articleMapper.selectById(articleId);
            if (article == null) {
                log.warn("文章不存在: articleId={}", articleId);
                return;
            }

            // 更新文章浏览量
            articleMapper.incrementViewCount(articleId);

            // 更新作者的用户统计 - 总浏览量
            try {
                userStatsMapper.updateUserStats(article.getAuthorId(), "total_view_count", 1);
                log.debug("更新作者统计浏览量: authorId={}", article.getAuthorId());
            } catch (Exception e) {
                log.warn("更新用户统计浏览量失败: authorId={}", article.getAuthorId(), e);
            }

            // 更新文章排行榜（如果启用Redis）
            try {
                rankingService.updateRankingItem(RankingType.ARTICLE, articleId);
            } catch (Exception e) {
                log.warn("更新文章排行榜失败: articleId={}", articleId, e);
                // 不影响主流程
            }

            // 更新作者排行榜
            try {
                rankingService.updateRankingItem(RankingType.AUTHOR, article.getAuthorId());
            } catch (Exception e) {
                log.warn("更新作者排行榜失败: authorId={}", article.getAuthorId(), e);
                // 不影响主流程
            }

            // 记录用户活动（如果有用户ID）
            if (userId != null) {
                recordUserActivity(userId, articleId, "VIEW_ARTICLE", ipAddress, userAgent);
            }

        } catch (Exception e) {
            log.error("增加文章浏览量失败: articleId={}", articleId, e);
        }
    }

    @Override
    public List<UserArticleDetailResponse.RelatedArticleInfo> getRelatedArticles(Long articleId, Integer limit) {
        log.debug("获取相关文章推荐: articleId={}, limit={}", articleId, limit);
        
        try {
            if (limit == null || limit <= 0) {
                limit = 5;
            }
            
            List<UserArticleDetailResponse.RelatedArticleInfo> relatedArticles = 
                articleMapper.selectRelatedArticles(articleId, limit);
            
            return relatedArticles != null ? relatedArticles : new ArrayList<>();
            
        } catch (Exception e) {
            log.error("获取相关文章推荐失败: articleId={}", articleId, e);
            return new ArrayList<>();
        }
    }

    @Override
    @Transactional
    public boolean toggleArticleLike(Long articleId, Long userId, boolean isLike) {
        log.info("切换文章点赞状态: articleId={}, userId={}, isLike={}", articleId, userId, isLike);

        try {
            // 获取文章信息
            Article article = articleMapper.selectById(articleId);
            if (article == null) {
                log.warn("文章不存在: articleId={}", articleId);
                return false;
            }

            if (isLike) {
                // 添加点赞
                boolean added = articleMapper.addUserLike(userId, articleId);
                if (added) {
                    // 更新文章点赞数
                    articleMapper.incrementLikeCount(articleId);

                    // 更新作者的用户统计 - 总点赞数
                    try {
                        userStatsMapper.updateUserStats(article.getAuthorId(), "total_like_count", 1);
                        log.debug("更新作者统计点赞数: authorId={}", article.getAuthorId());
                    } catch (Exception e) {
                        log.warn("更新用户统计点赞数失败: authorId={}", article.getAuthorId(), e);
                    }

                    // 更新文章排行榜
                    try {
                        rankingService.updateRankingItem(RankingType.ARTICLE, articleId);
                    } catch (Exception e) {
                        log.warn("更新文章排行榜失败: articleId={}", articleId, e);
                    }

                    // 更新作者排行榜
                    try {
                        rankingService.updateRankingItem(RankingType.AUTHOR, article.getAuthorId());
                    } catch (Exception e) {
                        log.warn("更新作者排行榜失败: authorId={}", article.getAuthorId(), e);
                    }

                    // 记录用户活动
                    recordUserActivity(userId, articleId, "LIKE_ARTICLE", null, null);

                    // 发送点赞通知
                    try {
                        notificationService.sendLikeNotification(userId, articleId, "article", article.getAuthorId());
                    } catch (Exception e) {
                        log.error("发送点赞通知失败: articleId={}, userId={}", articleId, userId, e);
                        // 通知发送失败不影响点赞操作
                    }
                }
                return added;
            } else {
                // 取消点赞
                boolean removed = articleMapper.removeUserLike(userId, articleId);
                if (removed) {
                    // 更新文章点赞数
                    articleMapper.decrementLikeCount(articleId);

                    // 更新作者的用户统计 - 总点赞数
                    try {
                        userStatsMapper.updateUserStats(article.getAuthorId(), "total_like_count", -1);
                        log.debug("更新作者统计点赞数: authorId={}", article.getAuthorId());
                    } catch (Exception e) {
                        log.warn("更新用户统计点赞数失败: authorId={}", article.getAuthorId(), e);
                    }

                    // 更新文章排行榜
                    try {
                        rankingService.updateRankingItem(RankingType.ARTICLE, articleId);
                    } catch (Exception e) {
                        log.warn("更新文章排行榜失败: articleId={}", articleId, e);
                    }

                    // 更新作者排行榜
                    try {
                        rankingService.updateRankingItem(RankingType.AUTHOR, article.getAuthorId());
                    } catch (Exception e) {
                        log.warn("更新作者排行榜失败: authorId={}", article.getAuthorId(), e);
                    }
                }
                return removed;
            }
        } catch (Exception e) {
            log.error("切换文章点赞状态失败: articleId={}, userId={}", articleId, userId, e);
            return false;
        }
    }

    @Override
    @Transactional
    public boolean toggleArticleCollect(Long articleId, Long userId, boolean isCollect) {
        log.info("切换文章收藏状态: articleId={}, userId={}, isCollect={}", articleId, userId, isCollect);

        try {
            // 获取文章信息
            Article article = articleMapper.selectById(articleId);
            if (article == null) {
                log.warn("文章不存在: articleId={}", articleId);
                return false;
            }

            if (isCollect) {
                // 添加收藏
                boolean added = articleMapper.addUserCollect(userId, articleId);
                if (added) {
                    // 更新文章收藏数
                    articleMapper.incrementCollectCount(articleId);

                    // 更新作者的用户统计 - 总收藏数
                    try {
                        userStatsMapper.updateUserStats(article.getAuthorId(), "total_collect_count", 1);
                        log.debug("更新作者统计收藏数: authorId={}", article.getAuthorId());
                    } catch (Exception e) {
                        log.warn("更新用户统计收藏数失败: authorId={}", article.getAuthorId(), e);
                    }

                    // 更新文章排行榜
                    try {
                        rankingService.updateRankingItem(RankingType.ARTICLE, articleId);
                    } catch (Exception e) {
                        log.warn("更新文章排行榜失败: articleId={}", articleId, e);
                    }

                    // 更新作者排行榜
                    try {
                        rankingService.updateRankingItem(RankingType.AUTHOR, article.getAuthorId());
                    } catch (Exception e) {
                        log.warn("更新作者排行榜失败: authorId={}", article.getAuthorId(), e);
                    }

                    // 记录用户活动
                    recordUserActivity(userId, articleId, "COLLECT_ARTICLE", null, null);

                    // 收藏通知已废弃,不再发送
                    // try {
                    //     notificationService.sendCollectNotification(userId, articleId, article.getAuthorId());
                    // } catch (Exception e) {
                    //     log.error("发送收藏通知失败: articleId={}, userId={}", articleId, userId, e);
                    //     // 通知发送失败不影响收藏操作
                    // }
                }
                return added;
            } else {
                // 取消收藏
                boolean removed = articleMapper.removeUserCollect(userId, articleId);
                if (removed) {
                    // 更新文章收藏数
                    articleMapper.decrementCollectCount(articleId);

                    // 更新作者的用户统计 - 总收藏数
                    try {
                        userStatsMapper.updateUserStats(article.getAuthorId(), "total_collect_count", -1);
                        log.debug("更新作者统计收藏数: authorId={}", article.getAuthorId());
                    } catch (Exception e) {
                        log.warn("更新用户统计收藏数失败: authorId={}", article.getAuthorId(), e);
                    }

                    // 更新文章排行榜
                    try {
                        rankingService.updateRankingItem(RankingType.ARTICLE, articleId);
                    } catch (Exception e) {
                        log.warn("更新文章排行榜失败: articleId={}", articleId, e);
                    }

                    // 更新作者排行榜
                    try {
                        rankingService.updateRankingItem(RankingType.AUTHOR, article.getAuthorId());
                    } catch (Exception e) {
                        log.warn("更新作者排行榜失败: authorId={}", article.getAuthorId(), e);
                    }
                }
                return removed;
            }
        } catch (Exception e) {
            log.error("切换文章收藏状态失败: articleId={}, userId={}", articleId, userId, e);
            return false;
        }
    }

    @Override
    public UserInteractionStatus getUserInteractionStatus(Long articleId, Long userId) {
        try {
            if (userId == null) {
                return new UserInteractionStatus(false, false, false);
            }

            Boolean isLiked = articleMapper.checkUserLike(userId, articleId);
            Boolean isCollected = articleMapper.checkUserCollect(userId, articleId);
            Boolean isFollowedAuthor = articleMapper.checkUserFollowAuthor(userId, articleId);

            return new UserInteractionStatus(
                isLiked != null && isLiked,
                isCollected != null && isCollected,
                isFollowedAuthor != null && isFollowedAuthor
            );
        } catch (Exception e) {
            log.error("获取用户交互状态失败: articleId={}, userId={}", articleId, userId, e);
            return new UserInteractionStatus(false, false, false);
        }
    }

    /**
     * 检查文章是否已发布
     */
    private boolean isArticlePublished(UserArticleDetailResponse article) {
        if (article == null || article.getStatus() == null) {
            return false;
        }
        
        try {
            ArticleStatus status = ArticleStatus.fromCode(article.getStatus());
            return status.isViewable();
        } catch (Exception e) {
            log.warn("无效的文章状态: status={}", article.getStatus());
            return false;
        }
    }

    /**
     * 计算阅读指标
     */
    private void calculateReadingMetrics(UserArticleDetailResponse article) {
        if (article.getContent() != null) {
            String content = article.getContent();
            
            // 计算字数（去除Markdown标记）
            String plainText = content.replaceAll("[#*`\\[\\]()_~]", "");
            int wordCount = plainText.length();
            article.setWordCount(wordCount);
            
            // 计算阅读时长（按每分钟300字计算）
            int readingTime = Math.max(1, wordCount / 300);
            article.setReadingTime(readingTime);
        }
    }

    /**
     * 处理文章标签
     */
    private void processArticleTags(UserArticleDetailResponse article) {
        try {
            // 获取文章关联的标签信息
            List<ArticleTag> articleTags = articleTagRelationService.getTagsByArticleId(article.getId());
            
            if (articleTags != null && !articleTags.isEmpty()) {
                List<UserArticleDetailResponse.TagInfo> tagInfoList = new ArrayList<>();
                
                for (ArticleTag tag : articleTags) {
                    UserArticleDetailResponse.TagInfo tagInfo = new UserArticleDetailResponse.TagInfo();
                    tagInfo.setId(tag.getId());
                    tagInfo.setName(tag.getName());
                    tagInfo.setColor(tag.getColor());
                    tagInfo.setDescription(tag.getDescription());
                    tagInfo.setIcon(tag.getIcon());
                    tagInfo.setUseCount(tag.getUseCount());
                    tagInfoList.add(tagInfo);
                }
                
                article.setTags(tagInfoList);
            } else {
                article.setTags(new ArrayList<>());
            }
        } catch (Exception e) {
            log.warn("处理文章标签失败: articleId={}", article.getId(), e);
            article.setTags(new ArrayList<>());
        }
    }

    /**
     * 设置SEO信息
     */
    private void setSeoInfo(UserArticleDetailResponse article) {
        UserArticleDetailResponse.SeoInfo seo = new UserArticleDetailResponse.SeoInfo();
        seo.setOgTitle(article.getTitle());
        seo.setOgDescription(article.getSummary());
        seo.setOgImage(article.getCoverImage());
        seo.setDescription(article.getSummary());
        article.setSeo(seo);
    }

    /**
     * 异步增加浏览量
     */
    private void incrementViewCountAsync(Long articleId, Long userId) {
        // 这里可以使用异步处理或消息队列，暂时同步处理
        incrementViewCount(articleId, userId, null, null);
    }

    @Override
    @Transactional
    public UserArticleResponse createArticle(UserArticleCreateRequest request, Long userId) {
        log.info("用户创建文章: userId={}, title={}", userId, request.getTitle());
        
        try {
            // 验证分类是否存在
            ArticleCategory category = categoryMapper.selectById(request.getCategoryId());
            if (category == null) {
                throw new RuntimeException("所选分类不存在");
            }

            // 创建文章实体
            Article article = new Article();
            article.setTitle(request.getTitle());
            article.setContent(request.getContent());
            article.setEditorTypes(request.getEditorTypes() != null ? request.getEditorTypes() : 1); // 默认为Markdown编辑器
            article.setCoverImage(request.getCoverImage());
            article.setAuthorId(userId);
            article.setCategoryId(request.getCategoryId());
            article.setIsOriginal(request.getIsOriginal());
            
            // 如果没有提供摘要，自动生成
            if (request.getSummary() == null || request.getSummary().trim().isEmpty()) {
                article.setSummary(generateSummary(request.getContent(), request.getEditorTypes()));
            } else {
                article.setSummary(request.getSummary());
            }
            
            // 设置状态和发布时间
            if (request.getPublishNow() != null && request.getPublishNow()) {
                article.setStatus(1); // 已发布
                article.setPublishTime(java.time.LocalDateTime.now());
            } else {
                article.setStatus(0); // 草稿
                article.setPublishTime(null);
            }
            
            // 初始化统计数据
            article.setViewCount(0);
            article.setLikeCount(0);
            article.setCommentCount(0);
            article.setCollectCount(0);
            article.setShareCount(0);
            article.setIsTop(0);
            
            // 保存文章
            int result = articleMapper.insert(article);
            if (result <= 0) {
                throw new RuntimeException("文章创建失败");
            }
            
            // 处理标签关联
            if (request.getTagIds() != null && !request.getTagIds().isEmpty()) {
                article.setTagCount(request.getTagIds().size());
                articleMapper.updateById(article);

                // 创建标签关联
                articleTagRelationService.setArticleTags(article.getId(), request.getTagIds());

                // 如果文章是发布状态，增加标签使用次数
                if (article.getStatus() == 1) {
                    for (Long tagId : request.getTagIds()) {
                        try {
                            tagManagementService.incrementTagUseCount(tagId);
                            log.debug("标签使用次数已增加: tagId={}", tagId);
                        } catch (Exception e) {
                            log.warn("增加标签使用次数失败: tagId={}", tagId, e);
                        }
                    }
                    log.info("文章发布，已更新 {} 个标签的使用次数", request.getTagIds().size());
                }
            } else {
                article.setTagCount(0);
                articleMapper.updateById(article);
            }

            // 如果文章是发布状态，更新用户统计 - 文章数
            if (article.getStatus() == 1) {
                try {
                    userStatsMapper.updateUserStats(userId, "article_count", 1);
                    log.debug("更新用户统计文章数: userId={}", userId);
                } catch (Exception e) {
                    log.warn("更新用户统计文章数失败: userId={}", userId, e);
                }
            }

            // 记录用户活动
            recordUserActivity(userId, article.getId(), "CREATE_ARTICLE", null, null);

            log.info("文章创建成功: articleId={}, title={}", article.getId(), article.getTitle());
            return convertToUserArticleResponse(article);
            
        } catch (Exception e) {
            log.error("创建文章失败: userId={}, title={}", userId, request.getTitle(), e);
            throw new RuntimeException("创建文章失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional
    public UserArticleResponse updateArticle(UserArticleUpdateRequest request, Long userId) {
        log.info("用户更新文章: userId={}, articleId={}", userId, request.getId());
        
        try {
            // 检查文章是否存在且属于当前用户
            Article existingArticle = articleMapper.selectById(request.getId());
            if (existingArticle == null) {
                throw new RuntimeException("文章不存在");
            }
            if (!existingArticle.getAuthorId().equals(userId)) {
                throw new RuntimeException("无权限修改此文章");
            }
            
            // 验证分类是否存在
            ArticleCategory category = categoryMapper.selectById(request.getCategoryId());
            if (category == null) {
                throw new RuntimeException("所选分类不存在");
            }

            // 更新文章信息
            Article article = new Article();
            article.setId(request.getId());
            article.setTitle(request.getTitle());
            article.setContent(request.getContent());
            article.setEditorTypes(request.getEditorTypes() != null ? request.getEditorTypes() : existingArticle.getEditorTypes()); // 保持原有编辑器类型或使用新的
            article.setCoverImage(request.getCoverImage());
            article.setCategoryId(request.getCategoryId());
            article.setIsOriginal(request.getIsOriginal());
            
            // 如果没有提供摘要，自动生成
            if (request.getSummary() == null || request.getSummary().trim().isEmpty()) {
                article.setSummary(generateSummary(request.getContent(), article.getEditorTypes()));
            } else {
                article.setSummary(request.getSummary());
            }
            
            // 设置状态和发布时间
            if (request.getPublishNow() != null && request.getPublishNow()) {
                article.setStatus(1); // 已发布
                if (existingArticle.getPublishTime() == null) {
                    article.setPublishTime(java.time.LocalDateTime.now());
                }
            } else {
                article.setStatus(0); // 草稿
            }
            
            // 更新文章
            int result = articleMapper.updateById(article);
            if (result <= 0) {
                throw new RuntimeException("文章更新失败");
            }
            
            // 更新标签关联
            if (request.getTagIds() != null) {
                // 获取旧标签列表
                List<Long> oldTagIds = articleTagRelationService.getTagIdsByArticleId(request.getId());
                
                // 设置新的标签关联（会先删除旧的再创建新的）
                articleTagRelationService.setArticleTags(request.getId(), request.getTagIds());
                
                // 更新标签使用次数（仅当文章是发布状态时）
                boolean isPublished = article.getStatus() == 1;
                if (isPublished) {
                    updateTagUseCounts(oldTagIds, request.getTagIds());
                }
                
                article.setTagCount(request.getTagIds().size());
                articleMapper.updateById(article);
            }
            
            // 记录用户活动
            recordUserActivity(userId, request.getId(), "UPDATE_ARTICLE", null, null);
            
            log.info("文章更新成功: articleId={}, title={}", request.getId(), request.getTitle());
            
            // 返回更新后的文章信息
            Article updatedArticle = articleMapper.selectById(request.getId());
            return convertToUserArticleResponse(updatedArticle);
            
        } catch (Exception e) {
            log.error("更新文章失败: userId={}, articleId={}", userId, request.getId(), e);
            throw new RuntimeException("更新文章失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional
    public boolean deleteArticle(Long articleId, Long userId) {
        log.info("用户删除文章: userId={}, articleId={}", userId, articleId);
        
        try {
            // 检查文章是否存在且属于当前用户
            Article article = articleMapper.selectById(articleId);
            if (article == null) {
                throw new RuntimeException("文章不存在");
            }
            if (!article.getAuthorId().equals(userId)) {
                throw new RuntimeException("无权限删除此文章");
            }
            
            // 软删除：更新状态为已删除
            Article updateArticle = new Article();
            updateArticle.setId(articleId);
            updateArticle.setStatus(2); // 已删除
            
            int result = articleMapper.updateById(updateArticle);
            if (result <= 0) {
                return false;
            }
            
            // 如果是发布状态的文章，减少标签使用次数和用户统计
            if (article.getStatus() == 1) {
                List<Long> tagIds = articleTagRelationService.getTagIdsByArticleId(articleId);
                if (tagIds != null && !tagIds.isEmpty()) {
                    for (Long tagId : tagIds) {
                        try {
                            tagManagementService.decrementTagUseCount(tagId);
                            log.debug("标签使用次数已减少: tagId={}", tagId);
                        } catch (Exception e) {
                            log.warn("减少标签使用次数失败: tagId={}", tagId, e);
                        }
                    }
                    log.info("文章删除，已更新 {} 个标签的使用次数", tagIds.size());
                }

                // 更新用户统计 - 减少文章数和相关统计
                try {
                    userStatsMapper.updateUserStats(userId, "article_count", -1);
                    // 减少总浏览量、点赞数、评论数、收藏数
                    if (article.getViewCount() != null && article.getViewCount() > 0) {
                        userStatsMapper.updateUserStats(userId, "total_view_count", -article.getViewCount().intValue());
                    }
                    if (article.getLikeCount() != null && article.getLikeCount() > 0) {
                        userStatsMapper.updateUserStats(userId, "total_like_count", -article.getLikeCount());
                    }
                    if (article.getCommentCount() != null && article.getCommentCount() > 0) {
                        userStatsMapper.updateUserStats(userId, "total_comment_count", -article.getCommentCount());
                    }
                    if (article.getCollectCount() != null && article.getCollectCount() > 0) {
                        userStatsMapper.updateUserStats(userId, "total_collect_count", -article.getCollectCount());
                    }
                    log.debug("更新用户统计（删除文章）: userId={}", userId);
                } catch (Exception e) {
                    log.warn("更新用户统计失败: userId={}", userId, e);
                }
            }

            // 删除标签关联
            articleTagRelationService.removeAllArticleTags(articleId);

            // 记录用户活动
            recordUserActivity(userId, articleId, "DELETE_ARTICLE", null, null);

            log.info("文章删除成功: articleId={}", articleId);
            return true;
            
        } catch (Exception e) {
            log.error("删除文章失败: userId={}, articleId={}", userId, articleId, e);
            return false;
        }
    }

    @Override
    public List<UserArticleResponse> getUserArticles(Long userId, Integer status, Long current, Long size) {
        log.info("获取用户文章列表: userId={}, status={}, current={}, size={}", userId, status, current, size);
        
        try {
            // 设置默认分页参数
            if (current == null || current < 1) current = 1L;
            if (size == null || size < 1) size = 10L;
            
            Long offset = (current - 1) * size;
            
            List<Article> articles = articleMapper.selectUserArticles(userId, status, offset, size);
            
            List<UserArticleResponse> responses = new ArrayList<>();
            for (Article article : articles) {
                responses.add(convertToUserArticleResponse(article));
            }
            
            return responses;
            
        } catch (Exception e) {
            log.error("获取用户文章列表失败: userId={}", userId, e);
            return new ArrayList<>();
        }
    }

    @Override
    @Transactional
    public boolean publishDraft(Long articleId, Long userId) {
        log.info("发布草稿文章: userId={}, articleId={}", userId, articleId);
        
        try {
            // 检查文章是否存在且属于当前用户
            Article article = articleMapper.selectById(articleId);
            if (article == null) {
                throw new RuntimeException("文章不存在");
            }
            if (!article.getAuthorId().equals(userId)) {
                throw new RuntimeException("无权限发布此文章");
            }
            // 检查文章状态，可以发布的状态：草稿、已下架、审核拒绝
            ArticleStatus currentStatus = ArticleStatus.fromCode(article.getStatus());
            if (!currentStatus.canPublish()) {
                throw new RuntimeException("当前状态的文章不能发布，支持发布的状态：草稿、已下架、审核拒绝");
            }
            
            // 更新文章状态
            Article updateArticle = new Article();
            updateArticle.setId(articleId);
            updateArticle.setStatus(ArticleStatus.PUBLISHED.getCode()); // 已发布
            updateArticle.setPublishTime(java.time.LocalDateTime.now());
            
            int result = articleMapper.updateById(updateArticle);
            if (result <= 0) {
                return false;
            }
            
            // 增加关联标签的使用次数
            List<Long> tagIds = articleTagRelationService.getTagIdsByArticleId(articleId);
            if (tagIds != null && !tagIds.isEmpty()) {
                for (Long tagId : tagIds) {
                    try {
                        tagManagementService.incrementTagUseCount(tagId);
                        log.debug("标签使用次数已增加: tagId={}", tagId);
                    } catch (Exception e) {
                        log.warn("增加标签使用次数失败: tagId={}", tagId, e);
                    }
                }
                log.info("草稿发布，已更新 {} 个标签的使用次数", tagIds.size());
            }

            // 更新用户统计 - 文章数
            try {
                userStatsMapper.updateUserStats(userId, "article_count", 1);
                log.debug("更新用户统计文章数: userId={}", userId);
            } catch (Exception e) {
                log.warn("更新用户统计文章数失败: userId={}", userId, e);
            }

            // 记录用户活动
            recordUserActivity(userId, articleId, "PUBLISH_ARTICLE", null, null);

            log.info("草稿发布成功: articleId={}", articleId);
            return true;
            
        } catch (Exception e) {
            log.error("发布草稿失败: userId={}, articleId={}", userId, articleId, e);
            return false;
        }
    }

    @Override
    @Transactional
    public boolean withdrawArticle(Long articleId, Long userId) {
        log.info("用户下架文章: userId={}, articleId={}", userId, articleId);
        
        try {
            // 检查文章是否存在且属于当前用户
            Article article = articleMapper.selectById(articleId);
            if (article == null) {
                throw new RuntimeException("文章不存在");
            }
            if (!article.getAuthorId().equals(userId)) {
                throw new RuntimeException("无权限下架此文章");
            }
            
            // 检查文章状态，只有已发布的文章才能下架
            ArticleStatus currentStatus = ArticleStatus.fromCode(article.getStatus());
            if (!currentStatus.canWithdraw()) {
                throw new RuntimeException("只能下架已发布状态的文章");
            }
            
            // 更新文章状态为已下架
            Article updateArticle = new Article();
            updateArticle.setId(articleId);
            updateArticle.setStatus(ArticleStatus.WITHDRAWN.getCode());
            
            int result = articleMapper.updateById(updateArticle);
            if (result <= 0) {
                return false;
            }
            
            // 记录用户活动
            recordUserActivity(userId, articleId, "ARTICLE_WITHDRAWN", null, null);
            
            log.info("文章下架成功: articleId={}", articleId);
            return true;
            
        } catch (Exception e) {
            log.error("文章下架失败: userId={}, articleId={}", userId, articleId, e);
            return false;
        }
    }

    /**
     * 根据编辑器类型生成文章摘要
     * @param content 文章内容
     * @param editorTypes 编辑器类型 1-Markdown编辑器 2-富文本编辑器
     * @return 摘要文本
     */
    private String generateSummary(String content, Integer editorTypes) {
        return HtmlUtils.generateSummary(content, editorTypes);
    }

    /**
     * 转换为用户文章响应DTO
     */
    private UserArticleResponse convertToUserArticleResponse(Article article) {
        UserArticleResponse response = new UserArticleResponse();
        response.setId(article.getId());
        response.setTitle(article.getTitle());
        response.setSummary(article.getSummary());
        response.setContent(article.getContent());
        response.setCoverImage(article.getCoverImage());
        response.setViewCount(article.getViewCount());
        response.setLikeCount(article.getLikeCount());
        response.setCommentCount(article.getCommentCount());
        response.setCollectCount(article.getCollectCount());
        response.setShareCount(article.getShareCount());
        response.setIsOriginal(article.getIsOriginal());
        response.setIsTop(article.getIsTop());
        response.setStatus(article.getStatus());
        response.setPublishTime(article.getPublishTime());
        response.setCreateTime(article.getCreateTime());
        response.setUpdateTime(article.getUpdateTime());
        
        // 设置分类信息
        if (article.getCategoryId() != null) {
            try {
                ArticleCategory category = categoryMapper.selectById(article.getCategoryId());
                if (category != null) {
                    UserArticleResponse.CategoryInfo categoryInfo = new UserArticleResponse.CategoryInfo();
                    categoryInfo.setId(category.getId());
                    categoryInfo.setName(category.getName());
                    categoryInfo.setDescription(category.getDescription());
                    categoryInfo.setIcon(category.getIcon());
                    response.setCategory(categoryInfo);
                }
            } catch (Exception e) {
                log.warn("获取文章分类信息失败: categoryId={}", article.getCategoryId(), e);
            }
        }
        
        // 设置标签信息
        try {
            List<ArticleTag> tags = articleTagRelationService.getTagsByArticleId(article.getId());
            if (tags != null && !tags.isEmpty()) {
                List<UserArticleResponse.TagInfo> tagInfos = new ArrayList<>();
                for (ArticleTag tag : tags) {
                    UserArticleResponse.TagInfo tagInfo = new UserArticleResponse.TagInfo();
                    tagInfo.setId(tag.getId());
                    tagInfo.setName(tag.getName());
                    tagInfo.setColor(tag.getColor());
                    tagInfos.add(tagInfo);
                }
                response.setTags(tagInfos);
            }
        } catch (Exception e) {
            log.warn("获取文章标签信息失败: articleId={}", article.getId(), e);
        }
        
        return response;
    }

    /**
     * 记录用户活动
     */
    private void recordUserActivity(Long userId, Long articleId, String activityType, String ipAddress, String userAgent) {
        try {
            // 记录用户活动，这里需要调用UserActivityService
            log.debug("记录用户活动: userId={}, articleId={}, activityType={}", userId, articleId, activityType);
        } catch (Exception e) {
            log.warn("记录用户活动失败: userId={}, articleId={}", userId, articleId, e);
        }
    }

    /**
     * 更新标签使用次数（处理标签变更）
     * @param oldTagIds 旧标签ID列表
     * @param newTagIds 新标签ID列表
     */
    private void updateTagUseCounts(List<Long> oldTagIds, List<Long> newTagIds) {
        if (oldTagIds == null) oldTagIds = new ArrayList<>();
        if (newTagIds == null) newTagIds = new ArrayList<>();
        
        // 找出需要减少使用次数的标签（在旧列表中但不在新列表中）
        List<Long> tagsToDecrement = new ArrayList<>(oldTagIds);
        tagsToDecrement.removeAll(newTagIds);
        
        // 找出需要增加使用次数的标签（在新列表中但不在旧列表中）
        List<Long> tagsToIncrement = new ArrayList<>(newTagIds);
        tagsToIncrement.removeAll(oldTagIds);
        
        // 减少使用次数
        for (Long tagId : tagsToDecrement) {
            try {
                tagManagementService.decrementTagUseCount(tagId);
                log.debug("标签使用次数已减少: tagId={}", tagId);
            } catch (Exception e) {
                log.warn("减少标签使用次数失败: tagId={}", tagId, e);
            }
        }
        
        // 增加使用次数
        for (Long tagId : tagsToIncrement) {
            try {
                tagManagementService.incrementTagUseCount(tagId);
                log.debug("标签使用次数已增加: tagId={}", tagId);
            } catch (Exception e) {
                log.warn("增加标签使用次数失败: tagId={}", tagId, e);
            }
        }
        
        if (!tagsToDecrement.isEmpty() || !tagsToIncrement.isEmpty()) {
            log.info("标签使用次数更新完成: 减少{}个标签, 增加{}个标签", 
                tagsToDecrement.size(), tagsToIncrement.size());
        }
    }
    /**
     * 检查用户是否是文章作者
     */
    private boolean isArticleAuthor(Long articleId, Long userId) {
        if (userId == null || articleId == null) {
            return false;
        }
        try {
            Article article = articleMapper.selectById(articleId);
            return article != null && article.getAuthorId() != null && article.getAuthorId().equals(userId);
        } catch (Exception e) {
            log.error("检查文章作者权限失败: articleId={}, userId={}", articleId, userId, e);
            return false;
        }
    }
}
